<template>
    <div>
        <p>用户名：<input type="text" v-model="username"></p>
        <p>密  码：<input type="text" v-model="password"></p>
        <p><input type="button" value="登录" @click="apps()"></p>
        <p><input type="button" value="无token访问" @click="no_token()"></p>
    </div>
</template>

<script>
import axios from "axios" 
export default {
    name:"login",
    data(){
        return{
            username:"",
            password:"",
            headers:"",
        }
    },
    methods:{
        apps(){
            var data= new FormData()
            data.append("username",this.username)
            data.append("password",this.password)
            axios({
                url:"http://127.0.0.1:8000/users/v1/login/",
                method:"post",
                data:data,
                headers:{
                    "Authorization":"JWT " + sessionStorage.getItem("jwt_token")
                }
            }).then(res=>{
                console.log(res)
                sessionStorage.setItem("id",res.data.userid)
                console.log("id",sessionStorage.getItem("id"))
                if(res.data.token){
                    let token = res.data.token;
                    localStorage.setItem("token",token)
                    alert("登录成功")
                    this.$router.push({path:"/show"})
                }else{
                    alert("没有登录 或登录失败无法获取用户信息")
                }
                // sessionStorage.setItem("jwt_token",res.data.token)
                // console.log("jwt_token",sessionStorage.getItem("jwt_token"))
            })
        },
        yes_token(){
            axios({
                url:"http://127.0.0.1:8000/users/v1/list/",
                method:"get",
                headers:{
                    "Authorization":"JWT " + sessionStorage.getItem("jwt_token")
                }
            }).then(res=>{
                console.log(res.data)
            })
        },
        no_token(){
            var data= new FormData()
            data.append("username",this.username)
            data.append("password",this.password)
            axios({
                url:"http://127.0.0.1:8000/users/v1/login/",
                method:"post",
                data:data,
            }).then(res=>{
                console.log(res)
                    alert("没有登录 或登录失败无法获取用户信息")
            })
        }
    }
}
</script>

